﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace UdpPeer.Assets
{
    /// <summary>
    /// 实现一下INotifyPropertyChanged接口的基类
    /// </summary>

    public class NotifyPropertyBase : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public void OnPropertyChanged(string propertyName)
        {

            if (PropertyChanged != null)
            {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }

        }
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

     

    }

    public static class NotifyPropertyBaseEx
    {

        /// <summary>
        /// 注册当前事件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <typeparam name="U">属性类型</typeparam>
        /// <param name="npb"></param>
        /// <param name="exp"></param>
        public  static void PropertyChangedRegist<T,U>(this T npb,  Expression<Func<T,U>>   exp) where T : NotifyPropertyBase, new()
        {

            string _PropertyName = GetPropertyName(exp);

            npb.OnPropertyChanged(_PropertyName);
        }


        //得到属性的名称

        public static string GetPropertyName(LambdaExpression exp)
        {

            string _pName = "";
            if (exp.Body is MemberExpression)
            {

                _pName = (exp.Body as MemberExpression).Member.Name;

            }

            else if (exp.Body is UnaryExpression)
            {
                _pName = ((exp.Body as UnaryExpression).Operand as MemberExpression).Member.Name;
            }

            return _pName;

        }

    }
}
